package com.qk.interceptor;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        if(url.contains("/login")){
            return true;
        }
        String token = request.getHeader("token");
        if(token==null){
            response.setStatus(401);
            return false;
        }
        try{
            Claims claims = JwtUtils.parseToken(token);
            Integer id =claims.get("id",Integer.class);
            log.info("用户id为：{}",id);
            CurrentUserHoler.setCurrentUser( id);
        }catch (Exception e){
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        CurrentUserHoler.removeCurrentUser();
    }
}
